package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/page")
    public R<Map> pageQuery(Integer page, Integer pageSize, String name) {
        //进行分页查询  构造分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        //添加过滤条件
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        qw.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, qw);
        //通过info获取结果
        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();

        Map data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        return R.success(data);
    }

    /**
     * 用于完成用户登录的方法
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //没有查询到结果
        if (emp == null) {
            return R.error("登录失败");
        }
        //判断是否为空
        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码错误");
        }
        //密码比对  不一致
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误,登陆失败");
        }
        //查看员工状态是否为禁用
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        //登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee, HttpSession session) {
        //日志
        log.info("新增员工,员工信息:{}", employee.toString());

        //检查数据,判断哪些需要处理
        //设置初始密码,进行md5加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        /*//创建时间和更改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户id
        Long employeeId = (Long) session.getAttribute("employee");
        //创建人和修改人是当前登录人
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);*/

        //1.调用业务层保存数据
        boolean save = employeeService.save(employee);
        //2.返回结果
        if (save) {
            return R.success("新增员工成功!");
        } else {
            return R.error("保存失败");
        }
    }

    /**
     * 根据id修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpServletRequest request) {
        log.info(employee.toString());

        /*Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);*/
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }
}
